<template>
  <div class="app-container">
    <el-alert title="请先查询房屋的缴费记录，确认截止期限，再进行收费操作" type="info" :closable="false" />
    <br />
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="区域" prop="deptId">
        <select-input dsCode="sys_dept_community" v-model="queryParams.deptId" style="width:180px"/>
      </el-form-item>      
      <el-form-item label="房屋" prop="roomId">
        <el-input v-model="queryRoomName" placeholder="请选择" readonly @click="doSelectRoom"/>
        <el-input v-model="queryParams.roomId" type="hidden"/>
      </el-form-item>
      <el-form-item label="支付方式" prop="payWay">
        <el-select v-model="queryParams.payWay" placeholder="请选择" clearable style="width:120px">
          <el-option
            v-for="dict in pay_way"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="单据状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择" clearable style="width:120px">
          <el-option
            v-for="dict in charge_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      
      <el-form-item label="收费日期" style="width: 308px">
        <el-date-picker
          v-model="daterangeStartDate"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button v-if="queryParams.roomId"
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['service:charge:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['service:charge:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="chargeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="单号" align="center" prop="num" />
      <el-table-column label="区域" align="center" prop="deptName" />
      <el-table-column label="房屋" align="center" prop="roomId">
        <template #default="scope">
          {{scope.row.buildingName}} - {{scope.row.unitNum}} - {{scope.row.roomName}}
        </template>
      </el-table-column>
      <el-table-column label="收费项目" align="center" prop="feeType">
        <template #default="scope">
          <dict-tag :options="fee_type" :value="scope.row.feeType"/>
        </template>
      </el-table-column>
      <el-table-column label="收费标准" align="center" prop="itemName" />
      <el-table-column label="折扣" align="center" prop="discountName" />
      <el-table-column label="应收金额" align="center" prop="feeShould" />
      <el-table-column label="实收金额" align="center" prop="feeReal" />
      <el-table-column label="退费金额" align="center" prop="feeReturn" />
      <el-table-column label="支付方式" align="center" prop="payWay">
        <template #default="scope">
          <dict-tag :options="pay_way" :value="scope.row.payWay"/>
        </template>
      </el-table-column>
      <el-table-column label="缴费期限" align="center" prop="startDate">
        <template #default="scope">
          {{scope.row.startDate}} ~ {{scope.row.endDate}}
        </template>
      </el-table-column>
      <el-table-column label="收费时间" align="center" prop="createTime" />
      <el-table-column label="单据状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="charge_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="说明" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['service:charge:edit']">修改说明</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改收费记录对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="chargeRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="区域" prop="deptId">
          <el-input v-model="form.deptId" type="hidden" placeholder="请输入区域" />
          <el-input v-model="form.deptName" readonly placeholder="请输入区域" />
        </el-form-item>
        <el-form-item label="房屋" prop="roomId">
          <el-input v-model="form.roomId" type="hidden" placeholder="请输入房屋" />
          <el-input :value="form.buildingName + ' - ' + form.unitNum + ' - ' + form.roomName" readonly placeholder="请输入房屋" />
        </el-form-item>
        <el-form-item label="面积" prop="area">
          <el-input v-model="roomInfo.area" readonly placeholder="房屋面积" />
        </el-form-item>
        <el-form-item label="最后缴费" prop="toDate">
          <el-input v-model="roomInfo.toDate" readonly placeholder="最后缴费时间,空是未缴费" />
        </el-form-item>
        <el-form-item label="收费标准" prop="itemId">
          <el-select v-model="form.itemId" placeholder="请选择收费标准" @change="changeItem">
            <el-option
              v-for="dict in chargeItemOptions"
              :key="dict.id"
              :label="dict.name"
              :value="dict.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="折扣" prop="discountId">
          <el-select v-model="form.discountId" placeholder="请选择收费标准" @change="changeDiscount" clearable>
            <el-option
              v-for="dict in chargeDiscountOptions"
              :key="dict.id"
              :label="dict.name"
              :value="dict.id"
            ></el-option>
          </el-select>
          <el-alert :title="'折扣使用条件: '+discountInfo.conditions" type="warning" :closable="false" v-if="form.discountId"/>
        </el-form-item>
        <el-form-item label="缴费月数" prop="feeMonth">
          <el-input-number v-model="form.feeMonth" placeholder="请输入缴费时长" @change="changeItem" :min="1"/>
        </el-form-item>
        <el-form-item label="开始日期" prop="startDate">
          <el-date-picker clearable
            v-model="form.startDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择开始日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束日期" prop="endDate">
          <el-date-picker clearable
            v-model="form.endDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="应收金额" prop="feeShould">
          <el-input-number v-model="form.feeShould" placeholder="请输入应收金额" />
        </el-form-item>
        <el-form-item label="实收金额" prop="feeReal">
          <el-input-number v-model="form.feeReal" placeholder="请输入实收金额" />
        </el-form-item>
        <el-form-item label="退费金额" prop="feeReturn">
          <el-input-number v-model="form.feeReturn"  placeholder="请输入退费金额" />
        </el-form-item>
        <el-form-item label="支付方式" prop="payWay">
          <el-select v-model="form.payWay" placeholder="请选择支付方式" >
            <el-option
              v-for="dict in pay_way"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="单据状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择">
            <el-option
              v-for="dict in charge_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="说明" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入说明" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <room-select :show="showRoomSelect" @select="selectRoom"/>
  </div>
</template>

<script setup name="Charge">
import { getToken } from "@/utils/auth";
import { listCharge, getCharge, delCharge, addCharge, updateCharge } from "@/api/service/charge";
import { selectChargeItem } from "@/api/service/chargeItem";
import { selectChargeDiscount } from "@/api/service/chargeDiscount";
import { getRoom } from "@/api/archive/room";
import SelectInput from "@/components/FormInput/Select";
import RoomSelect from "@/components/Selection/Room";

const { proxy } = getCurrentInstance();
const { pay_way, fee_type, charge_status } = proxy.useDict('pay_way', 'fee_type', 'charge_status');

const chargeList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const daterangeStartDate = ref([]);
const queryRoomName = ref("");
const showRoomSelect = ref(false);
const roomInfo = ref(null);
const chargeItemOptions = ref([]);
const chargeDiscountOptions = ref([]);
const discountInfo = ref(null);
const itemInfo = ref('');

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orderByColumn: 't.id',
    isAsc: 'desc',
    deptId: null,
    roomId: null,
    carId: null,
    itemId: null,
    feeType: 'room',
    discountId: null,
    payWay: null,
    startDate: null,
    endDate: null,
    status: null
  },
  rules: {
    deptId: [
      { required: true, message: "区域不能为空", trigger: "blur" }
    ],
    roomId: [
      { required: true, message: "房屋不能为空", trigger: "blur" }
    ],
    itemId: [
      { required: true, message: "收费标准不能为空", trigger: "blur" }
    ],
    feeMonth: [
      { required: true, message: "缴费月数不能为空", trigger: "blur" }
    ],
    feeShould: [
      { required: true, message: "应收金额不能为空", trigger: "blur" }
    ],
    feeReal: [
      { required: true, message: "实收金额不能为空", trigger: "blur" }
    ],
    payWay: [
      { required: true, message: "支付方式不能为空", trigger: "change" }
    ],
    startDate: [
      { required: true, message: "开始日期不能为空", trigger: "blur" }
    ],
    endDate: [
      { required: true, message: "结束日期不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "单据状态不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询收费记录列表 */
function getList() {
  loading.value = true;
  queryParams.value.params = {};
  if (null != daterangeStartDate && '' != daterangeStartDate) {
    queryParams.value.params["beginStartDate"] = daterangeStartDate.value[0];
    queryParams.value.params["endStartDate"] = daterangeStartDate.value[1];
  }
  listCharge(queryParams.value).then(response => {
    chargeList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

function doSelectRoom(){
  showRoomSelect.value = true;
}
function selectRoom(room){
  showRoomSelect.value = false;
  if(room == null){
    queryParams.value.roomId = null;
    queryRoomName.value = null;
    return;
  }
  queryParams.value.roomId = room.id;
  queryRoomName.value = room.name;
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    deptId: null,
    roomId: null,
    carId: null,
    itemId: null,
    feeType: 'room',
    discountId: null,
    feeMonth: 1,
    status: '1',
    feeShould: null,
    feeReal: null,
    feeReturn: null,
    payWay: null,
    startDate: null,
    endDate: null,
    remark: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  };
  proxy.resetForm("chargeRef");
  roomInfo.value = {};
  chargeItemOptions.value = [];
  chargeDiscountOptions.value = [];
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  queryParams.value.roomId = null;
  queryRoomName.value = null;
  daterangeStartDate.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  
  getRoom(queryParams.value.roomId).then(response => {
    roomInfo.value = response.data;
    form.value.roomId = response.data.id;
    form.value.buildingName = response.data.buildingName;
    form.value.unitNum = response.data.unitNum;
    form.value.roomName = response.data.name;
    form.value.deptId = response.data.deptId;
    form.value.deptName = response.data.deptName;
    open.value = true;
    title.value = "物业费: "+response.data.buildingName +' - ' + response.data.unitNum +' - ' + response.data.name;

    loadItemAndDiscount();
  });
}

/** 加载收费标准和折扣 */
function loadItemAndDiscount(){
  selectChargeItem({feeType:form.value.feeType, deptId:form.value.deptId}).then(response=>{
    chargeItemOptions.value = response.rows;
  })
  selectChargeDiscount({feeType:form.value.feeType, deptId:form.value.deptId}).then(response=>{
    chargeDiscountOptions.value = response.rows;
  })
}

/** 选择折扣后重，显示使用标准，并重新计费 */
function changeDiscount(){ 
  if(!form.value.discountId){
    discountInfo.value = {};
    changeItem();
    return;
  }
  for(let i=0;i<chargeDiscountOptions.value.length;i++){
    if(chargeDiscountOptions.value[i].id == form.value.discountId){
      discountInfo.value = chargeDiscountOptions.value[i];
      break;
    }
  }
  changeItem();
}

/** 选择收费标准后，重新计费 */
function changeItem() {
  if(form.value.itemId == null){
    form.value.feeShould = 0;
    form.value.feeReal = 0;
    return;
  }
  for(let i=0;i<chargeItemOptions.value.length;i++){
    if(chargeItemOptions.value[i].id == form.value.itemId){
      itemInfo.value = chargeItemOptions.value[i];
      break;
    }
  }  
  
  let fee = roomInfo.value.area * itemInfo.value.fee * form.value.feeMonth;
  form.value.feeShould = Math.round(fee * 100) / 100;
  if(discountInfo.value == null){
    fee = 0;
  }else if(discountInfo.value.type == '1'){
    //减免
    fee = discountInfo.value.fee;
  }else if(discountInfo.value.type == '2'){
    //折扣
    fee =  fee * (100 - discountInfo.value.fee) / 100;
  }else{
    fee = 0;
  }
  form.value.feeReal = form.value.feeShould - fee;
}

/** 修改按钮操作 */
function handleUpdate(row) {  
  proxy.$modal.prompt('修改收费单备注').then(function(val) {
    if(val.action != 'confirm'){
      return;
    }
    getCharge(row.id).then(response=>{
      response.data.remark = val.value;
      updateCharge(response.data).then(response => {
        proxy.$modal.msgSuccess("修改成功");
        getList();
      });
    })

  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["chargeRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateCharge(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addCharge(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('service/charge/export', {
    ...queryParams.value
  }, `charge_${new Date().getTime()}.xlsx`)
}

getList();
</script>
